<template>
  <div class="gateway">
    <gatewayNav></gatewayNav>
    <section class="banner">
      <img src="~@/assets/gateway/banner.jpg" alt="" />
    </section>
    <a-row :gutter="20" type="flex">
      <a-col :span="10" :push="2" class="right-container-wrapper width-ios-right">
        <a-spin :spinning="loading">
          <a-card class="msg-card card-no-padding">
            <section class="content" v-for="item in platformInfo" :key="item.levelTypeId">
              <h3 class="subTitH3">{{ item.levelTypeName }}</h3>
              <a-row :gutter="24" type="flex" class="sub-contet">
                <a-col :span="4" class="subNav" v-for="sub in item.children" :key="sub.id">
                  <div v-show="sub.key !== 'blockIcon'" style="cursor: pointer" class="contitl">
                    <img v-if="sub.fileInfoVO" :src="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + sub.fileInfoVO.fileId" @click="jumpRouter(sub)" class="img notice" alt="" />
                    <a-radio v-show="sub.selectStatus === 0" @click="bindUserFn(sub)" :checked="sub.bindUsed" class="radio" />
                    <h5 class="subTit" @click="jumpRouter(sub)">
                      <span v-if="sub.name !== '实时连线与超高清全景监控系统' && sub.name !== '组织与岗位绩效考核系统'">{{ sub.name }}</span>
                      <ellipsis :length="10" tooltip v-else>
                        {{ sub.name }}
                      </ellipsis>
                    </h5>
                  </div>
                  <div v-show="sub.key && sub.key === 'blockIcon' && item.levelTypeName === '公司级平台'">
                    <img :src="item.children.length > 13 ? sub.openUrl : sub.url" alt="" @click="openAll(item)" class="openIcon" />
                  </div>
                  <div v-show="sub.key && sub.key === 'blockIcon' && item.levelTypeName !== '公司级平台'">
                    <img :src="item.children.length > 7 ? sub.openUrl : sub.url" alt="" @click="openAll(item)" class="openIcon" />
                  </div>
                </a-col>
              </a-row>
            </section>
          </a-card>
        </a-spin>
      </a-col>
      <a-col :span="8" :push="2" class="right-container-wrapper width-ios-right">
        <a-card class="left-msg-card card-no-padding">
          <TodoList />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import TodoList from './components/gateway/TodoList.vue'
import Vue from 'vue'
import gatewayNav from './components/gateway/gatewayNav.vue'
import { getHomepageTree, bindUser } from '@/api/gateway'
import { mapState } from 'vuex'
import { Ellipsis } from '@/components'
export default {
  name: 'gateway',
  data() {
    return {
      platformInfo: [],
      token: '',
      imgUrlActive: null, //是否显示图片
      loading: true,
      initPlatformData: [], //初始化平台数据（操作展开隐藏）
      changeData: [] //初始化平台数据（操作展开隐藏）
    }
  },

  components: {
    TodoList,
    gatewayNav,
    Ellipsis
  },
  computed: {
    ...mapState({
      // 动态主路由
      mainMenu: state => state.permission.addRouters,
      rooterMenus: state => state.user.rooterMenus,
      menus: state => state.user.menus
    })
  },
  created() {
    this.token = Vue.getAcloudProvider().getAccessToken()
  },
  mounted() {
    this.initPlatform()
  },
  methods: {
    // 平铺菜单
    generateList() {
      const menusList = []
      const fun = list => {
        list.forEach(item => {
          const { children, ...others } = item
          menusList.push(others)
          if (!!item.children && !!item.children.length) {
            fun(item.children)
          }
        })
      }
      fun(this.menus)
      return menusList
    },
    // 根据url查找codes
    findCodesFromUrl(url) {
      const menusList = this.generateList()
      const current = menusList.find(item => item.raw.value === url)
      let codes = []
      const findCodes = item => {
        codes.unshift(item.raw.code)
        if (item.parentId && menusList.some(menu => menu.id === item.parentId)) {
          findCodes(menusList.find(menu => menu.id === item.parentId))
        }
      }
      if (!current || current.raw.value === '/index') {
        codes = []
      } else {
        findCodes(current)
      }
      return codes
    },
    //初始化平台
    async initPlatform() {
      let userInfo = JSON.parse(sessionStorage.getItem('ycloud-user_info'))
      let res = await getHomepageTree(userInfo?.employee?.id)
      console.log(res)
      let { code, data } = res
      if (code === 200 && data?.length > 0) {
        this.platformData = JSON.parse(JSON.stringify(data))
        this.platformData.forEach(item => {
          if (item.children.length > 12) {
            item.children.push({
              url: require('@/assets/gateway/Frame(7).png'),
              openUrl: require('@/assets/gateway/xiangshang.jpg'),
              key: 'blockIcon'
            })
          }
          if (item.levelTypeName !== '公司级平台' && item.children.length > 6) {
            item.children.push({
              url: require('@/assets/gateway/Frame(7).png'),
              openUrl: require('@/assets/gateway/xiangshang.jpg'),
              key: 'blockIcon'
            })
          }
        })
        this.platformInfo = data.map(item => {
          if (item.children.length > 12) {
            item.children = item.children.splice(0, 11)
            item.children.push({
              url: require('@/assets/gateway/Frame(7).png'),
              openUrl: require('@/assets/gateway/xiangshang.jpg'),
              key: 'blockIcon'
            })
          }
          if (item.levelTypeName !== '公司级平台' && item.children.length > 6) {
            item.children = item.children.splice(0, 5)
            item.children.push({
              url: require('@/assets/gateway/Frame(7).png'),
              openUrl: require('@/assets/gateway/xiangshang.jpg'),
              key: 'blockIcon'
            })
          }
          return item
        })
        this.changeData = JSON.parse(JSON.stringify(this.platformInfo))
        this.loading = false
      }
      this.loading = false
    },
    //展开平台元素
    openAll(val) {
      let isOpen = false
      if (val.children.length < 13 && val.levelTypeName === '公司级平台') {
        isOpen = true
      } else if (val.children.length < 7 && val.levelTypeName !== '公司级平台') {
        isOpen = true
      }
      if (isOpen) {
        this.platformInfo.forEach((item, index) => {
          if (val.levelTypeId === item.levelTypeId) {
            this.platformInfo[index].children = this.platformData[index].children
          }
        })
      } else {
        this.platformInfo.forEach((item, index) => {
          if (val.levelTypeId === item.levelTypeId) {
            this.platformInfo[index].children = this.changeData[index].children
          }
        })
      }
      this.$forceUpdate()
    },
    //地址跳转
    jumpRouter(value) {
      console.log(value, 2222)
      switch (value.name) {
        case '项目管控系统':
          this.$router.push({ path: '/index' })
          return false
          break
        case '客户服务系统':
          value.url = '/complaint/statistics'
          break
        case '数据看板系统':
          value.url = '/bi/overview'
          break
        case '组织与岗位绩效考核系统':
          value.url = '/satisfactionManagement/personCheckResult'
          break
        case '工程大数据系统':
          const token = Vue.getAcloudProvider().getAccessToken()
          const url = process.env.VUE_APP_PM_BASEURL + `/auth-userapi/yyzhzx/api/authority/v1/token?accessToken=${token}&callback=${process.env.VUE_APP_PM_DATA}`
          window.open(url, '_blank')
          return false
          break
        // case '实时连线与超高清全景监控系统':
        //   value.url = `${'https://build.cscecxn.com:4443' + '/dist/#/index/MoProject' + '?token'}=${token}&fgs=${this.$store.state.user.fgs}`
        //   window.open(value.url, '_blank')
        //   return false
        //   break
        case '实时连线与超高清全景监控系统':
          value.url = '/videoDocking/controPanel'
          break
        case '人力资源系统':
          let path = '/humanResources/home'
          const outMap = {
            '/cscec8b': 'https://app.cscec8b.com.cn/portalwebii/index.html#/login',
            '/humanResources/home': 'https://hr.cscecxn.com/api/auth/login_by_sso?sso=customer_sso&next=/%23/index&token=' + Vue.getAcloudProvider().getAccessToken() // 人力资源
          }
          const outPath = path.split('-')?.[0] || ''
          if (outMap[outPath]) {
            window.open(outMap[outPath], '_blank')
          }
          return false
        case '八局西南智选':
          const url1 = value.url + Vue.getAcloudProvider().getAccessToken()
          window.open(url1, '_blank')
          return false
        case '分包商资源库':
          // value.url = 'http://sub.zj8j.cdtest.cddpi.com?token=' + Vue.getAcloudProvider().getAccessToken()
          //  value.url = 'http://testpm.cscecxn.com/subcontractor?token=' + Vue.getAcloudProvider().getAccessToken()
          value.url = process.env.VUE_APP_PSUBCONTRACTOR
          break
        default:
          break
      }
      const activeCodes = this.findCodesFromUrl(value.url)
      if (!!activeCodes && !!activeCodes.length) {
        this.$store.commit('SET_ACTIVE_CODES', activeCodes)
        this.$storageSet('tabs', [{ title: value.name === '实时连线与超高清全景监控系统' ? '视频监控' : value.name, path: value.url, codes: activeCodes }])
        this.$router.push({ path: value.url })
      } else {
        this.$store.commit('SET_ACTIVE_CODES', [])
        if (value.selectStatus) {
          this.$router.push({ path: '/index' })
        } else {
          window.open(value.url, '_blank')
        }
      }
      // sessionStorage.setItem('orginHomeUrl', JSON.stringify(val))
    },
    //绑定
    async bindUserFn(data) {
      let isBind = null
      this.platformInfo.forEach(item => {
        item.children.forEach(sub => {
          if (data.id === sub.id) {
            this.$nextTick(() => {
              sub.bindUsed = !sub.bindUsed
            })
            isBind = !sub.bindUsed
          } else {
            sub.bindUsed = false
          }
        })
      })
      let userInfo = JSON.parse(sessionStorage.getItem('ycloud-user_info'))
      let params = {
        employeeId: userInfo?.employee?.id,
        homePageId: isBind ? data.id : ''
      }
      let res = await bindUser(params)
      if (res.code === 200 && isBind) {
        this.$message.success('绑定成功')
      }
      if (res.code === 200 && !isBind) {
        this.$message.success('解绑成功')
      }
    }
  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.card-no-padding {
  @{deep} .ant-card-body {
    padding: 0;
  }
}
.card-10-padding {
  @{deep} .ant-card-body {
    padding: 0;
  }
}
.gateway {
  width: 100%;
  height: 100%;
  overflow-x: auto;
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  .banner {
    margin-bottom: 18px;
    width: 100%;
    img {
      width: 100%;
      height: 240px;
    }
  }
  .msg-card {
    height: 590px;
    overflow-y: auto;
    // padding:20px;
    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }
    &::-webkit-scrollbar-thumb {
      border-radius: 6px;
      background: rgba(144, 147, 153, 0.5);
    }
    &::-webkit-scrollbar-track {
      border-radius: 5px;
      background: transparent;
    }
    .content {
      padding: 0 30px;
      padding-top: 24px;
      padding-bottom: 0;
    }
    h3 {
      font-size: 18px;
      padding-left: 12px;
      position: relative;
      margin-bottom: 20px;
      &::before {
        display: block;
        position: absolute;
        content: '';
        top: 0;
        left: 0;
        width: 9px;
        height: 22px;
        background: url('../../../src/assets/gateway/Group 25.png');
      }
    }
    & :last-child {
      border-bottom: none;
    }
  }
  .left-msg-card {
    height: 590px;
  }
  .sub-contet {
    // min-height: 176px;
    border-bottom: 1px solid #f5f7f8;
  }
  .subNav {
    margin-bottom: 20px;
    text-align: center;
    width: 16%;
    .img {
      margin-bottom: 8px;
      width: 37px;
      height: 40px;
      position: relative;
    }
    .radio {
      position: absolute;
      top: 4%;
      // left: 74%;
    }
    .subTit {
      min-width: 84px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      line-height: 22px;
      text-align: center;
      margin-bottom: 0;
    }
  }
  .openIcon {
    transform: translateY(-14px);
    padding: 30px;
  }
}
@media screen and (max-width: 1450px) {
  .indexPage-container {
    .ant-card {
      margin-bottom: 10px;
    }
    .todo-list-card {
      margin-bottom: 0;
    }
    padding: 10px;
    @{deep} .play-item-box {
      // height: 32vh;
      // .play-item-img {
      // width: 65%;
      // height: 100%;
      // }
      .play-item-article {
        // width: calc(100vw - 65vw - 16px);
        .article-title {
          font-size: 14px;
          line-height: 1.5em;
          padding-bottom: 10px;
        }
        .article-content {
          line-height: 1.5em;
          font-size: 12px;
        }
      }
    }
    @{deep} .custom-wrapper {
      .custom-content .custom-item {
        margin-right: 30px;
        .custom-item-icon {
          height: 36px;
          width: 36px;
          border-radius: 10px;
          font-size: 20px;
        }
        .custom-item-desc {
          font-size: 12px;
          padding-top: 0px;
        }
      }
      .custom-btns {
        .add-btn {
          height: 36px;
          width: 36px;
          border-radius: 10px;
          .add-btn-icon {
            font-size: 20px;
          }
        }
        .btn-desc {
          padding-top: 0px;
        }
      }
    }
    .todo-list-card {
      @{deep}.ant-card-body {
        padding: 10px;
      }
    }
  }
}
@media screen and (min-width: 1930px) {
  .indexPage-container {
    @{deep} .play-item-box {
      // height: 36vh;
      .play-item-article {
        .article-title {
          font-size: 26px;
          line-height: 1.5em;
          padding-bottom: 20px;
        }
        .article-content {
          line-height: 1.5em;
          font-size: 20px;
        }
      }
    }
    @{deep} .weather-info-wrapper {
      .date-info,
      .tip-info {
        font-size: 18px;
      }
    }
    @{deep} .extend-item-content {
      & > p {
        height: calc(var(--heightVh) * 0.05);
        line-height: calc(var(--heightVh) * 0.05);
        font-size: 18px;
      }
    }
  }
}
.width-ios-left {
  width: 63%;
}
.width-ios-right {
  width: 42%;
}
@media screen and (min-width: 1400px) and (max-width: 1440px) {
  .width-ios-left {
    width: 56%;
  }
  .width-ios-right {
    width: 42%;
  }
}

@media screen and (min-width: 1200px) and (max-width: 1370px) {
  .width-ios-left {
    width: 58%;
  }
  .width-ios-right {
    width: 43%;
  }
}
// .openIcon{
//   transform: translateY(-10px)
// }
.isNone {
  display: none;
}
.contitl {
  width: 90px;
  text-align: center;
}
</style>
